class Compiler {
  constructor(vm) {
    this.el = vm.$el;
    this.vm = vm;
    this.compile(this.el);
  }

  compile(el) {
    let childNodes = el.childNodes;

    Array.from(childNodes).forEach(node => {
      if (this.isTextNode(node)) {
        this.compileText(node);
      } else if (this.isElementNode(node)) {
        this.compileElement(node);
      }

      if (node.childNodes && node.childNodes.length) {
        this.compile(node);
      }
    });
  }

  compileElement(node) {
    Array.from(node.attributes).forEach(attr => {
      let attrName = attr.name;

      if (this.isDirective(attrName)) {
        let key = attr.value;
        attrName = attrName.substr(2);

        if (this.isEvent(attrName)) {
          this.eventUpdater(node, key, attrName);
        }

        this.update(node, key, attrName);
      }
    });
  }

  update(node, key, attrName) {
    let updateFn = this[attrName + 'Updater'];
    updateFn && updateFn.call(this, node, this.vm[key], key);
  }

  textUpdater(node, value, key) {
    node.textContent = value;
    new Watch(this.vm, key, newValue => {
      node.textContent = newValue;
    });
  }

  modelUpdater(node, value, key) {
    node.value = value;

    new Watch(this.vm, key, newValue => {
      node.value = newValue;
    });

    node.addEventListener('input', () => {
      this.vm[key] = node.value;
    });
  }

  // 新增 v-html 指令
  htmlUpdater(node, value, key) {
    node.innerHTML = value;

    new Watch(this.vm, key, newValue => {
      node.innerHTML = newValue;
    });
  }

  eventUpdater(node, value, key) {
    if (!key) {
      return;
    }

    let event = key.substr(3);
    this.onUpdater(node, value, event);
  }

  // 新增 v-on 指令
  onUpdater(node, value, key) {
    node.addEventListener(key, e => {
      this.vm[value](e);
    });
  }

  compileText(node) {
    let reg = /\{\{(.+?)\}\}/;
    let value = node.textContent;

    if (reg.test(value)) {
      let key = RegExp.$1.trim();
      node.textContent = value.replace(reg, this.vm[key]);

      new Watch(this.vm, key, newValue => {
        node.textContent = newValue;
      });
    }
  }

  isDirective(attrName) {
    return attrName.startsWith('v-');
  }

  isEvent(attrName) {
    return attrName.startsWith('on');
  }

  isTextNode(node) {
    return node.nodeType === 3;
  }

  isElementNode(node) {
    return node.nodeType === 1;
  }
}
